package com.zsl.controller.Admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.zsl.model.OrderInfo;
import com.zsl.service.OrderInfoService;
import com.zsl.service.impl.OrderInfoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "GetOrderInfo",urlPatterns = "/get/order/info/table")
public class GetOrderInfoTable extends HttpServlet {
    private OrderInfoService orderInfoService=new OrderInfoServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Map<String, Object> res = new HashMap<>();
        //获取数据
        String role = request.getParameter("role");
        //当无角色信息时
        if(role==null || role.equals("")){
            res.put("total","0");
            res.put("rows",new JSONArray());
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(res));
            return;
        }
        //用户请求
        if(role.equals("user")){
            //TODO 默认测试用户
            HttpSession session = request.getSession();
            String u_id=(String) session.getAttribute("id");
            try {
                res=orderInfoService.getUserOrderInfo(u_id);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                res.put("total","0");
                res.put("rows",new JSONArray());
            }finally {
                PrintWriter out = response.getWriter();
                out.write(JSON.toJSONString(res));
            }
        }
        //TODO 管理员请求
        else if(role.equals("admin")){
            try {
                res=orderInfoService.getAllOrderInfo();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                res.put("total","0");
                res.put("rows",new JSONArray());
            }finally {
                PrintWriter out = response.getWriter();
                out.write(JSON.toJSONString(res));
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
